package net.realsee.service.wcs.device.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import net.realsee.common.constant.CacheNames;
import net.realsee.common.enums.wcs.plc.PlcDataTypeEnum;
import net.realsee.common.utils.PlcUtil;
import net.realsee.common.utils.StringUtils;
import net.realsee.common.utils.redis.CacheUtils;
import net.realsee.common.utils.spring.SpringUtils;
import net.realsee.domain.wcs.device.WcsPlcTag;
import net.realsee.domain.wcs.device.bo.PlcReadWriteBo;
import net.realsee.domain.wcs.device.bo.PlcTagInfoBo;
import net.realsee.domain.wcs.device.bo.PlcTagTreeNode;
import net.realsee.domain.wcs.device.bo.WcsPlcTagBo;
import net.realsee.domain.wcs.device.vo.WcsPlcTagVo;
import net.realsee.framework.core.domain.PageQuery;
import net.realsee.framework.core.page.TableDataInfo;
import net.realsee.framework.plc.PlcOperateResult;
import net.realsee.mapper.wcs.device.WcsPlcTagMapper;
import net.realsee.service.wcs.device.IWcsPlcTagService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * IOT TAGService业务层处理
 *
 * @author realsee
 * @date 2023-08-11
 */
@RequiredArgsConstructor
@Service
public class WcsPlcTagServiceImpl extends ServiceImpl<WcsPlcTagMapper, WcsPlcTag> implements IWcsPlcTagService {

    private final WcsPlcTagMapper baseMapper;

    /**
     * 查询IOT TAG
     */
    @Override
    public WcsPlcTagVo selectVoById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询IOT TAG列表
     */
    @Override
    public TableDataInfo<WcsPlcTagVo> selectVoPage(WcsPlcTagBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WcsPlcTag> lqw = buildVoQueryWrapper(bo);
        Page<WcsPlcTagVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询IOT TAG列表
     */
    @Override
    public List<WcsPlcTagVo> selectVoList(WcsPlcTagBo bo) {
        LambdaQueryWrapper<WcsPlcTag> lqw = buildVoQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<WcsPlcTag> buildVoQueryWrapper(WcsPlcTagBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WcsPlcTag> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getId() != null, WcsPlcTag::getId, bo.getId());
        lqw.eq(StringUtils.isNotBlank(bo.getTagCode()), WcsPlcTag::getTagCode, bo.getTagCode());
        lqw.like(StringUtils.isNotBlank(bo.getTagName()), WcsPlcTag::getTagName, bo.getTagName());
        lqw.eq(StringUtils.isNotBlank(bo.getExtTagCode()), WcsPlcTag::getExtTagCode, bo.getExtTagCode());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), WcsPlcTag::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getAddr()), WcsPlcTag::getAddr, bo.getAddr());
        lqw.eq(StringUtils.isNotBlank(bo.getAddr2()), WcsPlcTag::getAddr2, bo.getAddr2());
        lqw.eq(StringUtils.isNotBlank(bo.getDevice()), WcsPlcTag::getDevice, bo.getDevice());
        lqw.eq(StringUtils.isNotBlank(bo.getChannel()), WcsPlcTag::getChannel, bo.getChannel());
        lqw.eq(StringUtils.isNotBlank(bo.getValue()), WcsPlcTag::getValue, bo.getValue());
        lqw.eq(StringUtils.isNotBlank(bo.getLastVal()), WcsPlcTag::getLastVal, bo.getLastVal());
        lqw.eq(bo.getStatus() != null, WcsPlcTag::getStatus, bo.getStatus());
        lqw.eq(bo.getLastSyncTime() != null, WcsPlcTag::getLastSyncTime, bo.getLastSyncTime());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkCenter()), WcsPlcTag::getWorkCenter, bo.getWorkCenter());
        lqw.eq(StringUtils.isNotBlank(bo.getLocation()), WcsPlcTag::getLocation, bo.getLocation());
        lqw.eq(bo.getListenFlag() != null, WcsPlcTag::getListenFlag, bo.getListenFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getRemark()), WcsPlcTag::getRemark, bo.getRemark());
        lqw.eq(StringUtils.isNotBlank(bo.getFuid()), WcsPlcTag::getFuid, bo.getFuid());
        lqw.eq(bo.getTextId() != null, WcsPlcTag::getTextId, bo.getTextId());
        lqw.eq(bo.getRefrenceId() != null, WcsPlcTag::getRefrenceId, bo.getRefrenceId());
        lqw.eq(bo.getUnitId() != null, WcsPlcTag::getUnitId, bo.getUnitId());
        lqw.eq(bo.getDelFlag() != null, WcsPlcTag::getDelFlag, bo.getDelFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateBy()), WcsPlcTag::getCreateBy, bo.getCreateBy());
        lqw.eq(bo.getCreateTime() != null, WcsPlcTag::getCreateTime, bo.getCreateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getUpdateBy()), WcsPlcTag::getUpdateBy, bo.getUpdateBy());
        lqw.eq(bo.getUpdateTime() != null, WcsPlcTag::getUpdateTime, bo.getUpdateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getDeleteBy()), WcsPlcTag::getDeleteBy, bo.getDeleteBy());
        lqw.eq(bo.getDeleteTime() != null, WcsPlcTag::getDeleteTime, bo.getDeleteTime());
        lqw.eq(bo.getRowVersionStamp() != null, WcsPlcTag::getRowVersionStamp, bo.getRowVersionStamp());
        return lqw;
    }

    /**
     * 新增IOT TAG
     */
    @Override
    public Boolean insertByBo(WcsPlcTagBo bo) {
        WcsPlcTag add = BeanUtil.toBean(bo, WcsPlcTag.class);
        return this.save(add);
    }

    /**
     * 修改IOT TAG
     */
    @Override
    public Boolean updateByBo(WcsPlcTagBo bo) {
        WcsPlcTag update = BeanUtil.toBean(bo, WcsPlcTag.class);
        return this.updateById(update);
    }

    /**
     * 批量删除IOT TAG
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        return this.removeBatchByIds(ids);
    }

    /**
     * 通过点位Code获取点位信息（会缓存）
     */
    @Cacheable(cacheNames = CacheNames.PLC_TAG_CODE, key = "#tagCode")
    @Override
    public PlcReadWriteBo getByTagCode(String tagCode) {
        return this.baseMapper.getByTagCode(tagCode);
    }

    /**
     * 查询TAG树
     */
    @Override
    public PlcTagTreeNode tree() {
        List<PlcTagInfoBo> tagInfoBoList = this.baseMapper.listPlcTagInfo();
        PlcTagTreeNode root = new PlcTagTreeNode("Root", "Root", null);
        for (PlcTagInfoBo tagInfoBo : tagInfoBoList) {
            PlcTagTreeNode channelNode = findOrCreate(root, tagInfoBo.getChannel(), tagInfoBo.getChannelName(), PlcDataTypeEnum.CHANNEL);
            PlcTagTreeNode deviceNode = findOrCreate(channelNode, tagInfoBo.getDevice(), tagInfoBo.getDeviceName(), PlcDataTypeEnum.DEVICE);
            if (ObjectUtil.isNotNull(deviceNode) && StrUtil.isNotBlank(tagInfoBo.getTag())) {
                deviceNode.getChildren().add(new PlcTagTreeNode(tagInfoBo.getTag(), tagInfoBo.getTagName(), PlcDataTypeEnum.TAG));
            }
        }
        return root;
    }

    private PlcTagTreeNode findOrCreate(PlcTagTreeNode parent, String code, String name, PlcDataTypeEnum dataType) {
        if (ObjectUtil.isNull(parent) || StrUtil.isBlank(code)) {
            return null;
        }
        for (PlcTagTreeNode child : parent.getChildren()) {
            if (StrUtil.equalsIgnoreCase(child.getCode(), code)) {
                return child;
            }
        }
        PlcTagTreeNode newNode = new PlcTagTreeNode(code, name, dataType);
        parent.getChildren().add(newNode);
        return newNode;
    }

    /**
     * 获取点位当前值
     * SpringUtils.getBean(this.getClass()这种写法，是因为缓存是通过AOP实现的，所以同一个类里调用会造成切面失效
     */
    @Override
    public PlcOperateResult currentContent(String tagCode) {
        return PlcUtil.read(SpringUtils.getBean(this.getClass()).getByTagCode(tagCode));
    }

    /**
     * 清除Tag缓存（任何修改和删除操作，都要调用该方法）
     */
    @Override
    public void cleanTagCache() {
        CacheUtils.clear(CacheNames.PLC_TAG_CODE);
    }

    /**
     * 写值
     */
    @Override
    public PlcOperateResult write(String tagCode, String value) {
        PlcReadWriteBo tag = SpringUtils.getBean(this.getClass()).getByTagCode(tagCode);
        if (ObjectUtil.isNotNull(tag)) {
            tag.setToWriteValue(value);
        }
        return PlcUtil.write(tag);
    }
}
